package me.seawenc.datastash.outputs.http;

import me.seawenc.datastash.outputs.AbstractConsumer;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * 可通过以下指令 开启测试端口
 * nc -l -k -p 8888
 */
public class HttpConsumer extends AbstractConsumer {

    private String apiUrl;


    public HttpConsumer(Properties props) {
        super(props);
        apiUrl = props.getProperty("output.http.apiUrl");
        System.out.println("apiUrl 地址为：" + apiUrl);
    }

    @Override
    public void consumption(String msg) {
        try {
            CloseableHttpClient client = HttpClients.createDefault();
            StringEntity s = new StringEntity(msg, StandardCharsets.UTF_8);
            s.setContentType("application/json; charset=utf-8");
            s.setContentEncoding("UTF-8");
            HttpPost post = new HttpPost(apiUrl);
            post.setEntity(s);
            client.execute(post);
        } catch (Exception e) {
            throw new RuntimeException("http请求失败:" + apiUrl);
        }
    }
}
